import { Shell } from '@xtail/shell'
import { send2FocusedWin } from '../utils'

const shells: Record<string, Shell> = {}

export const shellSessionOpen = async (channel: string) => {
  // 防止出现同一个 channel 两次不同连接使用不同的连接配置，两者之间发送冲突，后面的连接依旧使用之前的配置
  // 所以每次都创建新的连接实例，如果旧实例连接仍然存在则尝试关闭会话断开连接；旧实例关闭失败与否，都直接覆盖
  if (shells[channel] && shells[channel].isConnected) await shellSessionClose(channel)
  shells[channel] = new Shell()
  const onData = (data: string) => {
    // 参数 1：向哪个进程通信通道发送数据
    // 参数 2：数据
    // 参数 3：会话是否关闭
    send2FocusedWin(channel, data, false)
  }
  return shells[channel].connect(onData, onData, () =>
    send2FocusedWin(channel, '与本机建立的终端会话关闭', true)
  )
}

export type ShellSessionOpenType = typeof shellSessionOpen

export const shellSessionExec = async (channel: string, cmd: string) => {
  if (!shells[channel] || !shells[channel].isConnected) {
    const res = await shellSessionOpen(channel)
    if (!res.status) return res
  }
  return await shells[channel]!.exec(cmd)
}

export type ShellSessionExecType = typeof shellSessionExec

export const shellSessionClose = async (channel: string) => {
  if (!shells[channel]) return ResultUtil.genSuccessResult('本机终端会话已关闭')
  const res = shells[channel]!.close()
  if (res.status) Reflect.deleteProperty(shells, channel)
  return res
}

export type ShellSessionCloseType = typeof shellSessionClose
